package com.lsfb.signln.Location.SignIn;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.baidu.aip.face.AipFace;
import com.baidu.idl.face.platform.FaceStatusEnum;
import com.baidu.idl.face.platform.ui.FaceLivenessActivity;
import com.baidu.idl.face.platform.ui.utils.VolumeUtils;
import com.google.gson.Gson;
import com.lsfb.signln.Location.TaskMsg.Replenish.Signature.SignatureActivity;
import com.lsfb.signln.Login.Face.widget.DefaultDialog;
import com.lsfb.signln.Login.LoginActivity;
import com.lsfb.signln.R;
import com.lsfb.signln.Utils.Bconfig;
import com.lsfb.signln.Utils.LittleUtils;
import com.lsfb.signln.Utils.MyProgressDialog;
import com.lsfb.signln.Utils.URLString;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.Event.LsfbEvent;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.T;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

/**
 * 签到
 * Created by Administrator on 2018/2/1 0001.
 */

public class SignInActivity extends FaceLivenessActivity {

    private DefaultDialog mDefaultDialog;
    private String bestImagePath;
    private MyProgressDialog dialog;

    /**
     * 省市区行政编码
     */
    private String adcode;
    /**
     * 城市编码
     */
    private String citycode;
    /**
     * 参数校验值
     */
    private String token;

    private String SAVE_PIC_PATH = Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED) ? Environment.getExternalStorageDirectory().getAbsolutePath() : "/mnt/sdcard";
    private String pictureName = SAVE_PIC_PATH + "/face.jpg";//保存的确切位置

    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case 1000:
                    T.showLong(SignInActivity.this, "人脸校验不通过,请重试");
                    finish();
//                    showMessageDialog("人脸检测", "人脸校验不通过,请重试");
                    break;
                case 2000:
                    T.showLong(SignInActivity.this, "人脸识别系统出错，请使用签名定位");
                    break;
            }
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LsfbEvent.getInstantiation().register2(this);

        adcode = getIntent().getStringExtra("adcode");
        citycode = getIntent().getStringExtra("citycode");
        token = getIntent().getStringExtra("token");

        LsfbLog.e("文件名:" + pictureName);
        //判断文件是否存在
//        File file = new File(pictureName);
//        if (!file.exists()) {
        getData();
//        }

        dialog = new MyProgressDialog(this, "请稍等...");
    }

    @Override
    public void onLivenessCompletion(FaceStatusEnum status, String message, HashMap<String, String> base64ImageMap) {
        super.onLivenessCompletion(status, message, base64ImageMap);
        if (status == FaceStatusEnum.OK && mIsCompletion) {
            // showMessageDialog("活体检测", "检测成功");
            saveImage(base64ImageMap);
            sample(new AipFace(Bconfig.appid, Bconfig.apiKey, Bconfig.secretKey), bestImagePath);
//            Intent intent = new Intent();
//            intent.putExtra("file_path", bestImagePath);
//            setResult(Activity.RESULT_OK, intent);
//            finish();
        } else if (status == FaceStatusEnum.Error_DetectTimeout ||
                status == FaceStatusEnum.Error_LivenessTimeout ||
                status == FaceStatusEnum.Error_Timeout) {

            if (LittleUtils.face_num < 5) {
                LittleUtils.face_num++;
                handler.sendEmptyMessage(1000);
            } else {
                startActivity(new Intent(SignInActivity.this, SignatureActivity.class).putExtra("type", "2").putExtra("adcode", adcode).putExtra("citycode", citycode).putExtra("token", token));
                LittleUtils.face_num = 0;
            }
        }
    }

    private void saveImage(HashMap<String, String> base64ImageMap) {

        String bestimageBase64 = base64ImageMap.get("bestImage0");
        Bitmap bmp = base64ToBitmap(bestimageBase64);

        // 如果觉的在线校验慢，可以压缩图片的分辨率，目前没有压缩分辨率，压缩质量80%-100%，在neuxs5上大概30k
        try {
            // TODO: 2018/2/1 0001 得到目标文件 
            File file = File.createTempFile(UUID.randomUUID().toString(), ".jpg");
            FileOutputStream outputStream = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
            outputStream.close();

            bestImagePath = file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sample(final AipFace client, String bestImagePath) {
        // 传入可选参数调用接口
        final HashMap<String, String> options = new HashMap<String, String>();
        options.put("ext_fields", "qualities");
        options.put("image_liveness", "faceliveness,");
//        options.put("types", "7,13");
//        options.put("image_liveness", "faceliveness,faceliveness");
        options.put("types", "7,7");
        //参数为本地图片路径列表
        String path1 = bestImagePath;
//        String path2 = "/storage/emulated/0/Pictures/ngt/IMG_20180202_175911.jpg";
        String path2 = pictureName;
        final ArrayList<String> path = new ArrayList<String>();
        path.add(path1);
        path.add(path2);
        dialog.showdialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject res = client.match(path, options);
                dialog.hidedialog();
                Log.e("辣鸡百度", res.toString());

                try {
                    SiginBean bean = new SiginBean();
                    bean = new Gson().fromJson(res.toString(), SiginBean.class);

                    String[] live = bean.getExt_info().getFaceliveness().split(",");

                    if (Double.valueOf(bean.getResult().get(0).getScore()) > 80 && Double.valueOf(live[0]) > 0.834963 ) {
//                    if (Double.valueOf(bean.getResult().get(0).getScore()) > 80 && Double.valueOf(live[1]) > 0.834963) {
                        sign();
                    } else {
                        if (LittleUtils.face_num < 5) {
                            LittleUtils.face_num++;
                            handler.sendEmptyMessage(1000);
                        } else {
                            startActivity(new Intent(SignInActivity.this, SignatureActivity.class).putExtra("type", "2").putExtra("adcode", adcode).putExtra("citycode", citycode).putExtra("token", token));
                            LittleUtils.face_num = 0;
                        }
                    }
                } catch (IOError e) {
                    e.printStackTrace();
                    LsfbLog.e("手动解析错误" + e.getMessage());
                    handler.sendEmptyMessage(2000);
                    startActivity(new Intent(SignInActivity.this, SignatureActivity.class).putExtra("type", "2").putExtra("adcode", adcode).putExtra("citycode", citycode).putExtra("token", token));
                }

            }
        }).start();
    }

    private void showMessageDialog(String title, String message) {
        if (mDefaultDialog == null) {
            DefaultDialog.Builder builder = new DefaultDialog.Builder(this);
            builder.setTitle(title).
                    setMessage(message).
                    setNegativeButton("确认",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mDefaultDialog.dismiss();
//                                    Intent intent = new Intent();
//                                    intent.putExtra("file_path", bestImagePath);
//                                    setResult(Activity.RESULT_OK, intent);
//                                    finish();
                                    if (LittleUtils.face_num < 5) {
                                        // TODO: 2018/2/1 0001 刷新扫描控件
                                        if (mILivenessStrategy != null) {
                                            mILivenessStrategy.reset();
                                        }
                                        VolumeUtils.unRegisterVolumeReceiver(SignInActivity.this, mVolumeReceiver);
                                        mVolumeReceiver = null;
                                        stopPreview();
                                        setVolumeControlStream(AudioManager.STREAM_MUSIC);
                                        mVolumeReceiver = VolumeUtils.registerVolumeReceiver(SignInActivity.this, SignInActivity.this);
                                        if (mTipsTopView != null) {
                                            mTipsTopView.setText(R.string.detect_face_in);
                                        }
                                        startPreview();
                                    } else {
                                        startActivity(new Intent(SignInActivity.this, SignatureActivity.class).putExtra("type", "2").putExtra("adcode", adcode).putExtra("citycode", citycode).putExtra("token", token));
                                        LittleUtils.face_num = 0;
                                    }
                                }
                            });
            mDefaultDialog = builder.create();
            mDefaultDialog.setCancelable(true);
        }
        mDefaultDialog.dismiss();
        mDefaultDialog.show();
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LsfbEvent.getInstantiation().unregister2(this);
    }

    /**
     * 定位
     */
    public void sign() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("cityCode", citycode);
        hashMap.put("adcode", adcode);
        hashMap.put("signType", "0");
        hashMap.put("token", token);
        new BaseInternet().getData(URLString.SIGN, hashMap, String.class, new SignEvent(), true);
    }

    @EventAnnotation
    public void SignEvent(SignEvent event) {
        switch (event.getCode()) {
            case 200:
                T.showShort(this, "定位成功");
                finish();
                break;
            case 1006:
                T.showShort(this, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(this);
                startActivity(new Intent(this, LoginActivity.class));
                break;
            default:
                T.showLong(this, event.getMsg());
                finish();
                break;
        }
    }

    /**
     * 获取定位对比文件
     */
    private void getData() {
        HashMap<String, String> hashMap = new HashMap<String, String>();

        new BaseInternet().getData_Get(URLString.FACEIMG, hashMap, String.class, new SignInFileEvent2(), true, false);
    }

    @EventAnnotation
    public void SignInEvent(SignInFileEvent2 event) {
        switch (event.getCode()) {
            case 200:
                getHttpBitmap(URLString.IMAGES + event.getData());
                LsfbLog.e("头像: " + event.getData());
                break;
            case 1006:
                T.showShort(this, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(this);
                startActivity(new Intent(this, LoginActivity.class));
                break;
            default:
                T.showLong(this, "人脸识别源文件出错，请联系管理员并重新上传人脸信息");
                finish();
                break;
        }
    }

    /**
     * 下载图片
     *
     * @param url
     * @return
     */
    public void getHttpBitmap(final String url) {
        LsfbLog.e("下载图片");

        final Bitmap[] bitmap = {null};

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL pictureUrl = new URL(url);
                    InputStream in = pictureUrl.openStream();
                    bitmap[0] = BitmapFactory.decodeStream(in);
                    LsfbLog.e("下载成功？");
                    in.close();
                    savePicture(bitmap[0]);//保存
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    /**
     * 保存图片
     *
     * @param bitmap
     */
    public void savePicture(Bitmap bitmap) {
        LsfbLog.e("保存图片");

//        File file = new File(pictureName);
        FileOutputStream out;
        try {
            out = new FileOutputStream(pictureName);

//            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            LsfbLog.e("保存成功？");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
